﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using WebApiCoreJWTDemo.Common;

namespace WebApiCoreJWTDemo.Api.Filters
{
    public class CheckJWTFilter : ActionFilterAttribute
    {
        /// <summary>
        /// 表示是否检查登陆
        /// </summary>
        public bool IsCheck { get; set; } = true;

        /// <summary>
        /// 检查Session
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            bool ignoreCheckSession = filterContext.ActionDescriptor.FilterDescriptors
            .Select(f => f.Filter)
            .OfType<TypeFilterAttribute>()
            .Any(f => f.ImplementationType.Equals(typeof(IgnoreCheckJWTFilter)));
            if (ignoreCheckSession)
            {
                base.OnActionExecuting(filterContext);
                return;
            }

            if (IsCheck)
            {
                var claimIdentity = (ClaimsIdentity)filterContext.HttpContext.User.Identity;
                if (claimIdentity.Claims.Count() > 0 && JWTUtil.ValidateLogin(claimIdentity))
                {
                    base.OnActionExecuting(filterContext);
                }
                else
                {
                    filterContext.Result = new UnauthorizedResult();
                }
            }
            else
            {
                base.OnActionExecuting(filterContext);
            }
        }
    }
}
